package cn.codecang.mall.controller;

import cn.codecang.mall.common.aop.LogAnnotation;
import cn.codecang.mall.common.consts.ErrorCode;
import cn.codecang.mall.common.response.Result;
import cn.codecang.mall.entity.User;
import cn.codecang.mall.service.IUserService;
import cn.codecang.mall.vo.user.LoginReqVo;
import cn.codecang.mall.vo.user.LoginRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.transaction.KafkaTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Random;

/**
 * UserController
 *
 * @author xiaoluo
 * @date 2023/6/2 15:39
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "玩家模块")
public class UserController {

    final
    KafkaTemplate<String, String> kafka;

    private final IUserService userService;

    @Autowired
    public UserController(IUserService userService, KafkaTemplate<String, String> kafka) {
        Assert.notNull(userService, "IUserRepository must not be null");
        this.userService = userService;
        this.kafka = kafka;
    }

    /**
     * 登录
     *
     * @param request 请求
     * @return {@link Result}<{@link LoginRespVo}>
     */
    @PostMapping("/login")
    @ApiOperation("玩家登录")
    @Transactional(rollbackFor = Exception.class)
    public Result<LoginRespVo> login(@Validated LoginReqVo request) {
        return userService.login(request);
    }

    @GetMapping("/{id}")
    @ApiOperation("测试自定义异常并统一处理")
    public Result<Object> test(@PathVariable Long id) {
        int k = (int) (10 / id);
        if (id < 0) {
            return Result.error(ErrorCode.INVALID_PARAMETER);
        }
        User user = userService.getById(id);
        if (user == null) {
            return Result.error(ErrorCode.TOKEN_VERIFY);
        }
        return Result.success(user);
    }

    @LogAnnotation
    @GetMapping("/test/{input}")
    public String test(@PathVariable String input) {
        kafka.send("test", 0,"1", "test: " + input);
        if ("err".equals(input)) {
            throw new RuntimeException("input is err");
        }
        kafka.send("test", 0,"1", "test11111");
        return "test";
    }
}
